<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.1/axios.js"></script>
</head>

<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        // 获取按钮
        let btns = document.querySelectorAll('button');

        // 1. 声明一个空变量 - 用于存储cancel函数
        let cancel = null;
        // 2. 添加点击事件
        btns[0].onclick = async function() {
                try {
                    let data = await axios({
                        url: "http://api.zhibao.com/movies/1",
                        cancelToken: new axios.CancelToken((cb) => {
                            cancel = cb
                        })
                    })
                    console.log(data);
                } catch (err) {
                    console.log(err.name);
                    if (err.name === 'CanceledError') {
                        alert('您已取消请求');
                    }
                }
                // 3. 配置cancelToken:属性
                // 3.1 new axios.CancelToken((cb)=>{ cancel = cb })
            }
            // 4. 绑定取消请求点击事件
        btns[1].onclick = function() {
            // 4.1 判断cancel是否存在
            if (cancel) {
                // 4.2 存在即执行
                cancel()
            }
        }
    </script>
</body>

</html>